#!/usr/bin/python

from datetime import datetime, timezone, timedelta
import os
import locale
import sys
import time

from pypinyin import pinyin, Style


def set_locale():
    preferred_local = [
        'en_US.UTF-8',    ## ok for most linux
        'C.utf8',         ## ok for wls
        'zh_CN.UTF-8',
    ]
    #locale.setlocale(locale.LC_ALL, 'zh_CN.UTF-8')
    #locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
    for lc in preferred_local:
        try:
            locale.setlocale(locale.LC_ALL, lc)
            break
        except locale.Error as le:
            print(f'{lc}: {le}')

def is_full_width(c):
    ## hz is in [\u4e00 ~ \u9f5a]
    ## fw is in [\uff00 ~ \uff5b]
    return (u'\u4e00' <= c <= u'\u9fa5') or \
        (u'\uff00' <= c <= u'\uff5b')

def count_hz(mixed):
    return len([c for c in mixed if is_full_width(c)])

def len_w_hz(mixed):
    return len(mixed) + count_hz(mixed)

def ch_full2half(uchar):
    """ single character full to half """
    inside_code = ord(uchar)
    if inside_code == 0x3000:
        inside_code = 0x0020
    else:
        inside_code -= 0xfee0
    if inside_code < 0x0020 or inside_code > 0x7e:
        return uchar
    return chr(inside_code)

def get_abbr(hanzi):
    return ''.join(
        sum(
            pinyin(
                ''.join(map(ch_full2half, hanzi)),
                style=Style.FIRST_LETTER
            ), []
        )
    ).upper()

def get_localtime():
    t = datetime.utcnow().replace(tzinfo=timezone.utc)
    return t.astimezone(timezone(timedelta(hours=8)))

def get_time_tick():
    return round(time.time())

def get_system_proxies():
    return {
        p:os.getenv(p) for p in ['http_proxy', 'https_proxy']
    }

def safe_exit(ret, message=''):
    if message:
        print('safe_exit %s' % message)
    sys.exit(ret)

def dump_json_neat(_dict):
    import json
    buf = ''
    ret = []
    def is_too_long(s1, s2):
        return len(s1) + len(s2) > 80
    for line in json.dumps(_dict, indent=2).split('\n'):
        if line.rstrip().endswith('[') or \
           line.rstrip().endswith('{'):
            if buf:
                if True or is_too_long(buf, line.lstrip()):
                    ret.append(buf)
                    buf = line.rstrip()
                else:
                    buf += line.lstrip()
            else:
                #buf = line.rstrip()
                if line.rstrip().endswith('{'):
                    ret.append(line)
                else:
                    buf = line.rstrip()
            continue

        if line.lstrip().startswith(']') or \
            line.lstrip().startswith('}'):
            if buf:
                if True or is_too_long(buf, line.lstrip()):
#                    ret.append(buf)
#                    buf = line
                    ret.append(buf + line.lstrip())
                    buf = ''
                else:
                    buf += line.lstrip()
            else:
                 ret.append(line)
            continue

        if buf:
            if is_too_long(buf, line.lstrip()):
                ret.append(buf)
                buf = line
            else:
                buf += line.lstrip()
                if buf.endswith(','):
                    buf += ' '
        else:
            buf = line
    if buf:
        ret.append(buf)
    return ret

if __name__ == '__main__':
    print("system_proxies:")
    print(get_system_proxies())
    import json
    _dict = {'aa': 'bb',
             'arr': [1,2,3,4], "working_time": [["9:15", "11:31"],["13:00", "15:01"]],"data_source": "sina"}
    for ln in json.dumps(_dict, indent=2).split('\n'):
        print(ln)
    for ln in dump_json_neat(_dict):
        print(ln)

